package com.muye.dianli.activity;

import java.nio.charset.Charset;
import java.util.ArrayList;

import org.apache.http.entity.mime.content.StringBody;

import android.content.DialogInterface;
import android.content.DialogInterface.OnKeyListener;
import android.graphics.PixelFormat;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.muye.constant.C;
import com.muye.constant.U;
import com.muye.dianli.BaseActivity;
import com.muye.dianli.R;
import com.zvezda.algorithm.utils.MD5;
import com.zvezda.http.utils.HttpConst;
import com.zvezda.http.utils.KeyValue;
import com.zvezda.http.utils.RequestHttpListener;
import com.zvezda.http.utils.RequestHttpPostThread;

/**
 * 注册页面
 * 
 * @author TangChao
 * 
 */
public class RegisterActivity extends BaseActivity implements OnClickListener, OnKeyListener, TextWatcher
{
	/**
	 * 手机号输入框
	 */
	private EditText inputMobileEditText;
	
	/**
	 * 手机号
	 */
	private String moblieStr;
	
	/**
	 * 验证码输入框
	 */
	private EditText inputCodeEditText;
	
	/**
	 * 验证码
	 */
	private String codeStr;
	
	/**
	 * 用户名输入框
	 */
	private EditText inputUserNameEditText;
	
	/**
	 * 用户名
	 */
	private String userNameStr;
	
	/**
	 * 密码输入框
	 */
	private EditText inputPasswordEditText;
	
	/**
	 * 密码
	 */
	private String passwordStr;
	
	/**
	 * 请求数据线程
	 */
	private RequestHttpPostThread requestHttpPostThread;
	
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		getWindow().setFormat(PixelFormat.RGBA_8888);
		setContentView(R.layout.register_layout);
		createTitle();
		initWidget();
	}
	
	@Override
	protected void onDestroy()
	{
		super.onDestroy();
	}
	
	/**
	 * 初始化标题栏
	 */
	private void createTitle()
	{
		TextView titleName = (TextView) findViewById(R.id.title_bar_name_text_view);
		titleName.setText("注册");
		titleName.setTextColor(getResources().getColor(R.color.white));
		ImageView leftBtn = (ImageView) findViewById(R.id.title_bar_left_image_view);
		leftBtn.setImageResource(R.drawable.title_back_icon);
		leftBtn.setVisibility(View.VISIBLE);
		leftBtn.setOnClickListener(this);
	}
	
	/**
	 * 初始化控件
	 */
	private void initWidget()
	{
		// 信息输入框
		inputMobileEditText = (EditText) findViewById(R.id.register_layout_input_mobile_num);
		inputMobileEditText.addTextChangedListener(this);
		inputCodeEditText = (EditText) findViewById(R.id.register_layout_input_code);
		inputCodeEditText.addTextChangedListener(this);
		inputUserNameEditText = (EditText) findViewById(R.id.register_layout_input_user_name);
		inputUserNameEditText.addTextChangedListener(this);
		inputPasswordEditText = (EditText) findViewById(R.id.register_layout_input_password);
		inputPasswordEditText.addTextChangedListener(this);
		// 获取验证码
		TextView getCodeBtn = (TextView) findViewById(R.id.register_layout_get_code_btn);
		getCodeBtn.setOnClickListener(this);
		// 注册
		TextView registerBtn = (TextView) findViewById(R.id.register_layout_register);
		registerBtn.setOnClickListener(this);
	}
	
	/**
	 * 请求获取验证码
	 * 
	 */
	private void getCode()
	{
		C.openPragressDialog(this, this, R.string.in_request_data);
		ArrayList<KeyValue<String, Object>> paramsList = new ArrayList<KeyValue<String, Object>>();
		String str = C.APPID + moblieStr + C.CONSTANT;
		try
		{
			paramsList.add(new KeyValue<String, Object>("appid", new StringBody(C.APPID, Charset.forName("utf-8"))));
			paramsList.add(new KeyValue<String, Object>("phone", new StringBody(moblieStr, Charset.forName("utf-8"))));
			paramsList
					.add(new KeyValue<String, Object>("sign", new StringBody(MD5.getMD5_32(str), Charset.forName("utf-8"))));
			requestHttpPostThread = new RequestHttpPostThread(getCodeListener, U.GET_CODE, paramsList);
			requestHttpPostThread.start();
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
	}
	
	/**
	 * 请求获取验证码返回监听
	 */
	private RequestHttpListener getCodeListener = new RequestHttpListener()
	{
		
		@Override
		public void requestHttp(Message msg)
		{
			Bundle bundle = msg.getData();
			int result = bundle.getInt(HttpConst.ACTION_RESULT, HttpConst.ACTION_FAIL);
			if (result == HttpConst.ACTION_SUCCESS)
			{
				try
				{
					byte[] dataArr = bundle.getByteArray(HttpConst.DATA_ARR);
					String str = new String(dataArr, "utf-8");
				}
				catch (Exception e)
				{
					e.printStackTrace();
				}
				Message message = new Message();
				msg.what = 0;
				msg.arg1 = result;
				handler.sendMessage(message);
			}
		}
	};
	
	/**
	 * 请求注册
	 */
	private void register()
	{
		C.openPragressDialog(this, this, R.string.in_request_data);
		ArrayList<KeyValue<String, Object>> paramsList = new ArrayList<KeyValue<String, Object>>();
		String str = "3" + userNameStr + passwordStr + codeStr + C.CONSTANT;
		try
		{
			paramsList.add(new KeyValue<String, Object>("appId", new StringBody("3", Charset.forName("utf-8"))));
			paramsList.add(new KeyValue<String, Object>("name", new StringBody(userNameStr, Charset.forName("utf-8"))));
			paramsList.add(new KeyValue<String, Object>("pass", new StringBody(passwordStr, Charset.forName("utf-8"))));
			paramsList.add(new KeyValue<String, Object>("sms", new StringBody(codeStr, Charset.forName("utf-8"))));
			paramsList
					.add(new KeyValue<String, Object>("sign", new StringBody(MD5.getMD5_32(str), Charset.forName("utf-8"))));
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		requestHttpPostThread = new RequestHttpPostThread(registerListener, U.REGISTER, paramsList);
		requestHttpPostThread.start();
	}
	
	/**
	 * 请求注册返回监听
	 */
	private RequestHttpListener registerListener = new RequestHttpListener()
	{
		
		@Override
		public void requestHttp(Message msg)
		{
			Bundle bundle = msg.getData();
			int result = bundle.getInt(HttpConst.ACTION_RESULT, HttpConst.ACTION_FAIL);
			if (result == HttpConst.ACTION_SUCCESS)
			{
				byte[] dataArr = bundle.getByteArray(HttpConst.DATA_ARR);
				try
				{
					String str = new String(dataArr, "utf-8");
					Log.i(C.TAG, "注册结果----->" + str);
				}
				catch (Exception e)
				{
					e.printStackTrace();
				}
				Message message = new Message();
				message.what = 1;
				message.arg1 = result;
				handler.sendMessage(message);
			}
		}
	};
	
	/**
	 * 处理数据
	 */
	private Handler handler = new Handler()
	{
		@Override
		public void handleMessage(Message msg)
		{
			super.handleMessage(msg);
			C.closePragressDialog();
			switch (msg.what)
			{
				case 0:// 请求获取验证码
					switch (msg.arg1)
					{
						case HttpConst.ACTION_SUCCESS:
							
							break;
						case HttpConst.ACTION_FAIL:
							C.showToast(getApplicationContext(), R.string.fail_request_data);
							break;
					}
					break;
				case 1:// 注册
					switch (msg.arg1)
					{
						case HttpConst.ACTION_SUCCESS:
							finish();
							break;
						case HttpConst.ACTION_FAIL:
							break;
						default:
							break;
					}
					break;
				
				default:
					break;
			}
		}
		
	};
	
	@Override
	public void onClick(View v)
	{
		switch (v.getId())
		{
			case R.id.title_bar_left_image_view:
				finish();
				break;
			case R.id.register_layout_get_code_btn:// 获取验证码按钮
				if (moblieStr == null || moblieStr.length() != 11)
				{
					C.showToast(this, "请输入正确的手机号");
					return;
				}
				getCode();
				break;
			case R.id.register_layout_register:// 注册按钮
				if (moblieStr == null || moblieStr.equals(""))
				{
					C.showToast(this, "请输入手机号");
					return;
				}
				if (!(moblieStr.length() >= 11 && moblieStr.length() <= 12))
				{
					C.showToast(this, "请输入正确的手机号");
					return;
				}
				if (codeStr == null || codeStr.equals(""))
				{
					C.showToast(this, "请输入验证码");
					return;
				}
				if (codeStr.length() != 6)
				{
					C.showToast(this, "请输入正确的验证码");
					return;
				}
				if (userNameStr == null || userNameStr.equals(""))
				{
					C.showToast(this, "请输入用户名");
					return;
				}
				if (passwordStr == null || passwordStr.equals(""))
				{
					C.showToast(this, "请输入密码");
					return;
				}
				register();
				break;
			
			default:
				break;
		}
	}
	
	@Override
	public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event)
	{
		if (requestHttpPostThread != null)
		{
			requestHttpPostThread.interrupt();
			requestHttpPostThread.setRequestHttpListener(null);
		}
		return false;
	}
	
	@Override
	public void afterTextChanged(Editable s)
	{
		moblieStr = inputMobileEditText.getText().toString();
		codeStr = inputCodeEditText.getText().toString();
		userNameStr = inputUserNameEditText.getText().toString();
		passwordStr = inputPasswordEditText.getText().toString();
	}
	
	@Override
	public void beforeTextChanged(CharSequence s, int start, int count, int after)
	{
	}
	
	@Override
	public void onTextChanged(CharSequence s, int start, int before, int count)
	{
	}
	
}
